//
//  RegisterViewController.m
//  BaJieLvYouForIphone
//
//  Created by zhangwo on 16/8/12.
//  Copyright © 2016年 GuoBuGa. All rights reserved.
//

#import "RegisterViewController.h"
#import "LoginViewController.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

@synthesize nameView   = _nameView;
@synthesize profile = _profile;
@synthesize dutiesView = _dutiesView;
@synthesize departmentLabel = _departmentLabel;
@synthesize mobileView   = _mobileView;
@synthesize passwordView = _passwordView;
@synthesize registerButton = _registerButton;
@synthesize seccodeField   = _seccodeField;
@synthesize seccodeButton  = _seccodeButton;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"0xf2f2f2"]];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    UIImageView *bgImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT)];
    bgImage.image = [UIImage imageNamed:@"icon-bgIogin.png"];
    bgImage.userInteractionEnabled = YES;
    [self.view addSubview:bgImage];
    
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(20, 30, 20, 20)];
    backImage.image = [UIImage imageNamed:@"icon-return-back.png"];
    backImage.userInteractionEnabled=YES;
    [bgImage addSubview:backImage];
    UITapGestureRecognizer *singleTap =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [backImage addGestureRecognizer:singleTap];
    
    UIButton *loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(SWIDTH-100, 30, 80, 25)];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(showLogin) forControlEvents:UIControlEventTouchUpInside];
    [bgImage addSubview:loginBtn];
    
    UIImageView *registerView = [[UIImageView alloc] initWithFrame:CGRectMake(15, SWIDTH/2-80, SWIDTH-30, 364)];
    registerView.image = [UIImage imageNamed:@"icon-regist-image.png"];
    registerView.userInteractionEnabled = YES;
    
    _line = [[UIView alloc] initWithFrame:CGRectMake(0, 60, registerView.frame.size.width, 1)];
    _line.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
    [registerView addSubview:_line];
    
    _line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 121, registerView.frame.size.width, 1)];
    _line1.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
    [registerView addSubview:_line1];
    
    _line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 182, registerView.frame.size.width, 1)];
    _line2.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
    [registerView addSubview:_line2];
    
    _line3 = [[UIView alloc] initWithFrame:CGRectMake(0, 243, registerView.frame.size.width, 1)];
    _line3.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
    [registerView addSubview:_line3];
    
    _line4 = [[UIView alloc] initWithFrame:CGRectMake(0, 304, registerView.frame.size.width, 1)];
    _line4.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
    [registerView addSubview:_line4];
    
    _line5 = [[UIView alloc] initWithFrame:CGRectMake(registerView.frame.size.width-100, 10, 1, 40)];
    _line5.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
//    [registerView addSubview:_line5];
    
    [self.view addSubview:registerView];
    
    //用户名
    _nameView = [[LoginInputView alloc] initWithFrame:CGRectMake(0, 0, registerView.frame.size.width, 60)];
    _nameView.placeHolder = @"姓名";
//    _nameView.textField.delegate = self;
    [registerView addSubview:_nameView];
    
    //性别
//    _profile = [[UIButton alloc] initWithFrame:CGRectMake(registerView.frame.size.width-100, 0, 100, 60)];
//    [_profile setTitle:@"性别" forState:UIControlStateNormal];
//    [_profile setImage:[UIImage imageNamed:@"icon-trigonBtn-image.png"] forState:UIControlStateNormal];
//    [_profile setTitleColor:[UIColor colorWithHexString:@"0x0068DE"] forState:UIControlStateNormal];
//    [_profile setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 30)];
//    [_profile setImageEdgeInsets:UIEdgeInsetsMake(0, 60, 0, 10)];
//    [_profile addTarget:self action:@selector(sexChange:) forControlEvents:UIControlEventTouchUpInside];
//    [registerView addSubview:_profile];
    
    
    //职务
    _dutiesView = [[LoginInputView alloc] initWithFrame:CGRectMake(0, 61, registerView.frame.size.width, 60)];
    _dutiesView.placeHolder = @"职务";
//    _dutiesView.textField.delegate = self;
    [registerView addSubview:_dutiesView];
    
    //部门
    _departmentLabel = [[LoginInputView alloc] initWithFrame:CGRectMake(0, 121, registerView.frame.size.width, 60)];
    _departmentLabel.placeHolder = @"部门";
    _departmentLabel.textField.delegate = self;
//    _departmentLabel.textColor = [UIColor colorWithHexString:@"0x2480CE"];
//    _departmentLabel.inputView = _pickerView;
    [registerView addSubview:_departmentLabel];
    
    //手机号
    _mobileView = [[LoginInputView alloc] initWithFrame:CGRectMake(0, 182, registerView.frame.size.width, 60)];
    _mobileView.placeHolder = @"手机号";
//    _mobileView.textField.delegate = self;
    [registerView addSubview:_mobileView];
    
    //短信验证码
    _seccodeField = [[UITextField alloc] initWithFrame:CGRectMake(20, 243, registerView.frame.size.width/2+20, 60)];
    _seccodeField.placeholder = @"填写验证码";
    _seccodeField.returnKeyType = UIReturnKeyDone;
//    _seccodeField.delegate = self;
    _seccodeField.keyboardType = UIKeyboardTypeNumberPad;
    [registerView addSubview:_seccodeField];
    
    //发送验证码按钮
    _seccodeButton = [[UIButton alloc] initWithFrame:CGRectMake(registerView.frame.size.width/2+50, 253, 100, 40)];
    _seccodeButton.backgroundColor = [UIColor colorWithHexString:@"0x0068DE"];
    _seccodeButton.layer.cornerRadius = 10;
    [_seccodeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_seccodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [_seccodeButton.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [_seccodeButton addTarget:self action:@selector(sendSecCode) forControlEvents:UIControlEventTouchUpInside];
    [registerView addSubview:_seccodeButton];
    
    _registerButton = [DSXUI longButtonWithTitle:@"注册"];
    _registerButton.frame = CGRectMake(15, SWIDTH+150, SWIDTH-30, 50);
    [_registerButton setBackgroundImage:[UIImage imageNamed:@"icon-login-regist-image.png"] forState:UIControlStateNormal];
    [_registerButton addTarget:self action:@selector(checkRegister) forControlEvents:UIControlEventTouchUpInside];
    _registerButton.titleLabel.textColor = [UIColor redColor];
    [self.view addSubview:_registerButton];
    
    //密码输入框
    _passwordView = [[LoginInputView alloc] initWithFrame:CGRectMake(0, registerView.frame.size.height-60, registerView.frame.size.width, 60)];
    _passwordView.placeHolder = @"输入登录密码,至少6位";
    _passwordView.textField.secureTextEntry = YES;
//    _passwordView.textField.delegate = self;
    [registerView addSubview:_passwordView];
    
}

- (void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)showLogin{
    [self dismissViewControllerAnimated:NO completion:nil];
}

//性别选择
- (void)sexChange:(UIButton *)sender
{
//    UIActionSheet *sexSheet = [[UIActionSheet alloc]init];
//    [sexSheet addButtonWithTitle:@"男"];
//    [sexSheet addButtonWithTitle:@"女"];
//    [sexSheet addButtonWithTitle:@"取消"];
//    [sexSheet setCancelButtonIndex:2];
//    [sexSheet showInView:self.view];
//    [sexSheet setTag:223];
//    [sexSheet setDelegate:self];
}

- (void)setSex:(NSInteger)sex
{

}

//性别选择
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 223) {
        if (buttonIndex == 0) {
            [self setSex:1];
        }
        if (buttonIndex == 1) {
            [self setSex:0];
        }
    }
}

//获得焦点事件
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self departmentPickerView];
}

//失去焦点
-(void)textFieldDidEndEditing:(UITextField *)textField{
    [self.pickerView setHidden:YES];
}

#pragma - mark pickerView
///pickerView
- (void)departmentPickerView
{
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SHEIGHT-225, SWIDTH, 225)];
    _pickerView.showsSelectionIndicator = YES;
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_pickerView];
    
    _toolbarButton=[[UIToolbar alloc] initWithFrame:CGRectMake(0.0, SHEIGHT-265, SWIDTH, 40)];
    _toolbarButton.backgroundColor = [UIColor colorWithHexString:@"0xDEDEDE"];
    
    //左
    UIBarButtonItem *lefttem=[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(removePickerView)];
    lefttem.tintColor = [UIColor colorWithHexString:@"0x0068DE"];
    UIBarButtonItem *centerSpace=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    //右
    UIBarButtonItem *right=[[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(confirmPickerView)];
    right.tintColor = [UIColor colorWithHexString:@"0x0068DE"];
    _toolbarButton.items=@[lefttem,centerSpace,right];
    [self.view addSubview:_toolbarButton];
}

#pragma mark - 加载数据
- (void)loadDataSource
{
    [[DSXHttpManager sharedManager] GET:@"c=member&a=getdepartments" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([[responseObject objectForKey:@"errno"] intValue] == 0) {
                _departmentData = [responseObject objectForKey:@"data"];
                NSLog(@"%@",_departmentData);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

//一共多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

//每列对应多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [self.departmentData count];
}

//每列每行对应显示的数据是什么
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    //指定每行要展示的数据
    return self.departmentData[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
    cell.textLabel.text=@"asda";
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //获取对应列的数据
    NSString *name = self.departmentData [indexPath.row];
    //赋值
    if (indexPath.row == 0) {
        self.departmentLabel.text = name;
    }
    else if (indexPath.row == 1)
    {
        self.departmentLabel.text = name;
    }
    else if (indexPath.row == 2)
    {
        self.departmentLabel.text = name;
    }
    else if (indexPath.row == 3)
    {
        self.departmentLabel.text = name;
    }
    else
    {
        self.departmentLabel.text = name;
    }
//    switch (indexPath.row) {
//        case 0:
//            NSLog(@"click...");
//            [self.view addSubview:self.toolbarButton];
//            [self.view addSubview:self.pickerView];
//            break;
//            
//        default:
//            break;
//    }
}

-(void)confirmPickerView
{
    
}


-(void)removePickerView
{
    [_pickerView setHidden:YES];
    [_toolbarButton setHidden:YES];
}

- (void)sendSecCode{
    NSString *phone = _mobileView.text;
    if ([phone length] == 11) {
        [[DSXHttpManager sharedManager] GET:@"&c=member&a=sendseccode" parameters:@{@"phone":phone} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                _watingTime = 60;
                _seccodeButton.enabled = NO;
                [_seccodeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                [_seccodeButton setBackgroundImage:[UIImage imageNamed:@"icon-time.png"] forState:UIControlStateNormal];
                [_seccodeButton setTitle:@"重新发送(60)" forState:UIControlStateNormal];
                [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(wating:) userInfo:nil repeats:YES];
                [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleSuccess Message:@"验证码发送成功"];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
        
    }else {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"手机号码输入错误"];
    }
}

- (void)wating:(NSTimer *)timer{
    _watingTime--;
    [_seccodeButton setTitle:[NSString stringWithFormat:@"重新发送(%d)",_watingTime] forState:UIControlStateNormal];
    if (_watingTime < 1) {
        [timer invalidate];
        [_seccodeButton setEnabled:YES];
        [_seccodeButton setTitle:@"重新发送" forState:UIControlStateNormal];
        [_seccodeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_seccodeButton setBackgroundImage:[UIImage imageNamed:@"icon-yanzhengma.png"] forState:UIControlStateNormal];
    }
}

- (void)checkRegister{
    NSString *name = _nameView.text;
    NSString *duties = _dutiesView.text;
    NSString *department = _departmentLabel.text;
    NSString *mobile   = _mobileView.text;
    NSString *password = _passwordView.text;
    NSString *seccode  = _seccodeField.text;
    
    if (![name isName]) {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"用户名输入错误"];
        return;
    }
    
    if (![duties isPriviliges]) {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"职务输入错误"];
        return;
    }
    
    if (![department isDepartment]) {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"部门输入错误"];
        return;
    }
    
    if (![mobile isMobile]) {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"手机号码输入错误"];
        return;
    }
    
    if (![password isPassword]) {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"密码输入错误,至少6位"];
        return;
    }
    
    if ([seccode length] != 6) {
        [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"验证码输入错误"];
        return;
    }
    
    if (name && duties && department && mobile && password && seccode) {
        _registerButton.enabled = NO;
        NSDictionary *params = @{
                                 @"username":name,
                                 @"priviliges":duties,
                                 @"department":department,
                                 @"mobile":mobile,
                                 @"password":password,
                                 @"seccode":seccode,
                                 @"type":@"mobile"
                                 };
        [[DSXActivityIndicator sharedIndicator] showModalViewWithTitle:@"注册中..."];
        [[BJUserStatus sharedStatus] register:params success:^(id responseObject) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[DSXActivityIndicator sharedIndicator] hide];
                [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"注册成功"];
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        } failure:^(NSString *errorMsg) {
            _registerButton.enabled = YES;
            [[DSXActivityIndicator sharedIndicator] hide];
            [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:errorMsg];
        }];
    }
}

#pragma mark -
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
